package me.edzh.spring.bootstrap.utils;

import lombok.var;
import me.edzh.spring.bootstrap.utils.exception.ServiceException;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;

public class MathUtils {
    private static Random r = new Random();

    /**
     * 返回 [min, max]
     * @param excludeZero 为true, 则一定返回非0值
     */
    public static int random(int min, int max, boolean excludeZero) {
        if (excludeZero) {
            while (true) {
                int r = random(min, max);
                if (r != 0) return r;
            }
        } else {
            return r.nextInt(max - min + 1) + min;
        }
    }
    /**
     * 返回 [min, max]
     */
    public static int random(int min, int max) {
        return random(min, max, false);

    }

    /**
     * 返回 [min, max]
     */
    public static double random(double min, double max) {
        return (max - min) * r.nextDouble() + min;
    }

    @SafeVarargs
    public static <T extends Comparable<T>> T max(T ...input){
        return Arrays.asList(input).parallelStream().max(Comparable::compareTo).orElseThrow(() -> new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, ""));
    }

    @SafeVarargs
    public static <T extends Comparable<T>> T min(T ...input){
        return Arrays.asList(input).parallelStream().min(Comparator.naturalOrder()).orElseThrow(() -> new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, ""));
    }

    public boolean between(Comparable<Object> input, Comparable<Object> floor, Comparable<Object> ceiling) {
        if (input == null || (ceiling == null && floor == null)) return false;

        boolean biggerThanFloor = floor == null || input.compareTo(floor) >= 0;
        boolean lessThanCeiling = ceiling == null || ceiling.compareTo(input) >= 0;

        return biggerThanFloor && lessThanCeiling;
    }
}
